package com.su.dolphin.utils.mgr;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import android.text.TextUtils;

import com.su.dolphin.common.DpAppInfo;
import com.su.dolphin.utils.SDCardUtils;
import com.su.dolphin.utils.TimeUtil;

/**
 * Crash 日志的收集等
 * 
 * @author alex
 * 
 */
public class DpCrashManager
{
    
    private static final int MAX_LOG_FILES = 10;
    private static String FILE_PREFIX = ".log";
    
    public static void init() {
        Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
        // Register if not already registered
        if (!(currentHandler instanceof ExceptionHandler)) {
            Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(currentHandler));
        }
        //定时清理
        //        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //        scheduledExecutorService.schedule(new ClearLogTask(), 5, TimeUnit.SECONDS);
    }
    
    private static class ExceptionHandler implements Thread.UncaughtExceptionHandler
    {
        
        private Thread.UncaughtExceptionHandler previousHandler;
        
        public ExceptionHandler(Thread.UncaughtExceptionHandler handler) {
            this.previousHandler = handler;
        }
        
        public void uncaughtException(Thread thread, Throwable exception) {
            final Date now = new Date();
            final Writer result = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(result);
            
            exception.printStackTrace(printWriter);
            
            try {
                
                String logDir = SDCardUtils.PATH_CRASH_LOG;
                if (TextUtils.isEmpty(logDir)) {
                    return;
                }
                
                //String filename = UUID.randomUUID().toString();
                String filename = TimeUtil.getCurrentTimeInString(TimeUtil.yyyyMMddHHmmss.get());
                String path = logDir + File.separator + filename + FILE_PREFIX;
                
                BufferedWriter write = new BufferedWriter(new FileWriter(path));
                write.write("Package: " + DpAppInfo.APP_PACKAGE + "\n");
                write.write("Version: " + DpAppInfo.APP_VERSION + "\n");
                write.write("Android: " + DpAppInfo.PHONE_ANDROID_VERSION + "\n");
                write.write("Manufacturer: " + DpAppInfo.PHONE_MANUFACTURER + "\n");
                write.write("Model: " + DpAppInfo.PHONE_MODEL + "\n");
                write.write("IMEI: " + DpAppInfo.PHONE_IMEI + "\n");
                write.write("DeviceId: " + DpAppInfo.PHONE_DEVICEID + "\n");
                write.write("Date: " + now + "\n");
                write.write("\n");
                write.write(result.toString());
                write.flush();
                write.close();
                
                onlyLeftTenLogFilesInStorage();
            }
            catch (Exception another) {
                
            }
            finally {
                previousHandler.uncaughtException(thread, exception);
            }
        }
    }
    
    //每次crash之后都清理crash日志
    private static void onlyLeftTenLogFilesInStorage() {
        String[] files = searchForStackTraces();
        if (files == null) {
            return;
        }
        int length = files.length;
        if (length > MAX_LOG_FILES) {
            for (int i = MAX_LOG_FILES; i < length; i++) {
                new File(files[i]).delete();
            }
        }
    }
    
    private static String[] searchForStackTraces() {
        String path = SDCardUtils.PATH_CRASH_LOG;
        if (TextUtils.isEmpty(path)) {
            return new String[0];
        }
        // Try to create the files folder if it doesn't exist
        File dir = new File(path);
        // Filter for ".stacktrace" files
        FilenameFilter filter = new FilenameFilter()
        {
            public boolean accept(File dir, String name) {
                return name.endsWith(FILE_PREFIX);
            }
        };
        String[] files = dir.list(filter);
        for (int i = 0; i < files.length; i++) {
            files[i] = path + File.separator + files[i];
        }
        // desc sort arrays, then delete the longest file
        Arrays.sort(files, new Comparator<String>()
        {
            @Override
            public int compare(String aFilePath, String bFilePath) {
                long aDate = new File(aFilePath).lastModified();
                long bDate = new File(bFilePath).lastModified();
                return (aDate > bDate ? -1 : 1);
            }
        });
        return files;
    }
    //    private static class ClearLogTask implements Runnable
    //    {
    //        
    //        @Override
    //        public void run() {
    //            onlyLeftTenLogFilesInStorage();
    //        }
    //    }
}
